package com.tim.app.ui.activity.some_homepage;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyView;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.netease.nim.session.SessionHelper;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.AlbumResult;
import com.tim.app.server.result.DynamicListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.server.result.UserRelationStatedResult;
import com.tim.app.server.result.UserinfoDetailResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.activity.ModtifyUserInfoActivity;
import com.tim.app.ui.activity.setting.EditAvatarActivity;
import com.tim.app.ui.adapter.someone_homepage.HomepageDynamicAdapter;
import com.tim.app.ui.dialog.TipDialog;
import com.tim.app.ui.popup.ReportSomeonePop;
import com.tim.app.ui.view.SomeOneHomepageHeadView;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.ui.widget.imagepick.ui.ImageGridActivity;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewActivity;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewTopicActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 某人主页
 */
public class SomeoneHomepageActivity extends BaseActivity implements LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "SomeoneHomepageActivity";

    private LinearLayout llBottomContainer;
    private LinearLayout llTalkContainer;
    private LinearLayout llFollowContainer;

    private AppBarLayout appbar;
    private ImageView ivBack, ivReport, ivEdit;
    private TextView tvUserName;
    private View vLine;
    private ImageView ivHeaderBg;

    private RoundedImageView rivAvatar;
    private TextView tvHomepageUserName;
    private TextView tvAgeInfo;
    private TextView tvLevel;
    private TextView tvDesc;

    private User currentUser;
    private boolean isFromPush = false;

    private LoadMoreRecycleViewContainer load_more;

    private WrapRecyclerView wrvDynamic;
    private HomepageDynamicAdapter adapter;
    private List<Dynamic> dataList;

    private SomeOneHomepageHeadView headView;

    private ImagePickerManager imagePicker;

    private List<String> imageList;

    public static void start(Context context, User user, boolean isFromPush) {
        Intent intent = new Intent(context, SomeoneHomepageActivity.class);
        if (null == user || TextUtils.isEmpty(user.getUserId())) {
            return;
        }
        intent.putExtra(AppKey.USER, user);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_someone_page;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        llBottomContainer = (LinearLayout) findViewById(R.id.llBottomContainer);
        llTalkContainer = (LinearLayout) findViewById(R.id.llTalkContainer);
        llFollowContainer = (LinearLayout) findViewById(R.id.llFollowContainer);
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivReport = (ImageView) findViewById(R.id.ivReport);
        ivEdit = (ImageView) findViewById(R.id.ivEdit);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        ivHeaderBg = (ImageView) findViewById(R.id.ivHeaderBg);
        vLine = findViewById(R.id.vLine);

        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);
        tvHomepageUserName = (TextView) findViewById(R.id.tvHomepageUserName);
        tvAgeInfo = (TextView) findViewById(R.id.tvAgeInfo);
        tvLevel = (TextView) findViewById(R.id.tvLevel);
        tvDesc = (TextView) findViewById(R.id.tvDesc);

        ivBack.setOnClickListener(this);
        ivReport.setOnClickListener(this);
        ivEdit.setOnClickListener(this);
        rivAvatar.setOnClickListener(this);
        llTalkContainer.setOnClickListener(this);
        llFollowContainer.setOnClickListener(this);

        currentUser = (User) getIntent().getSerializableExtra(AppKey.USER);
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);


        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvDynamic = (WrapRecyclerView) findViewById(R.id.wrvDynamic);

        wrvDynamic.setOverScrollMode(View.OVER_SCROLL_NEVER);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        if (imageList == null) {
            imageList = new ArrayList<>();
        }
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        wrvDynamic.setLayoutManager(layoutManager);

        EmptyView emptyView = (EmptyView) LayoutInflater.from(this).inflate(R.layout.empty_layout, null);
        emptyView.setLayoutParams(new RecyclerView.LayoutParams(-1, (int) RT.getDensity() * 228));
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(currentUser.getUserId())) {
            emptyView.setData(R.drawable.ic_empty_dynamic, "我还没有动态");
        } else {
            if (currentUser.getSex() == 1) {
                emptyView.setData(R.drawable.ic_empty_dynamic, "他还没有动态");
            } else {
                emptyView.setData(R.drawable.ic_empty_dynamic, "她还没有动态");
            }
        }

        wrvDynamic.setEmptyView(emptyView);

        headView = (SomeOneHomepageHeadView) LayoutInflater.from(this).inflate(R.layout.some_one_homepage_head_view, wrvDynamic, false);

        wrvDynamic.addHeaderView(headView);
        wrvDynamic.setHasFixedSize(true);
        wrvDynamic.setNestedScrollingEnabled(false);
        adapter = new HomepageDynamicAdapter(this, dataList);
        wrvDynamic.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_5)).visibilityProvider(adapter).build());

        adapter.setOnItemClickListener(this);
        wrvDynamic.setAdapter(adapter);

        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(AppKey.IMAGE_SIZE);
        imagePicker.setCrop(true);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {  //展开状态
                    tvUserName.setTextColor(getResources().getColor(R.color.white));
                    ivBack.setImageResource(R.drawable.ic_back_white);
                    ivReport.setImageResource(R.drawable.ic_more_white);
                    ivEdit.setImageResource(R.drawable.ic_edit_white);
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    vLine.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                    ivReport.setImageResource(R.drawable.ic_more);
                    ivEdit.setImageResource(R.drawable.ic_edit_black);
                    tvUserName.setTextColor(getResources().getColor(R.color.text_title_color));
                } else {//中间状态
                    vLine.setVisibility(View.GONE);
                    tvUserName.setTextColor(getResources().getColor(R.color.white));
                }

//                int maxScroll = appBarLayout.getTotalScrollRange();
//                float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll;
//                if (percentage > 0.7f) {
//                    vLine.setVisibility(View.VISIBLE);
//                } else {
//                    vLine.setVisibility(View.GONE);
//                }
            }
        });

        refreshUi(currentUser);
        EventManager.ins().registListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().registListener(EventTag.ADD_ABLUM, eventListener);
        EventManager.ins().registListener(EventTag.ABLUM_CHANGED, eventListener);
        EventManager.ins().registListener(EventTag.DELETE_ABLUM, eventListener);
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.DO_CANCEL_FOLLOW, eventListener);
        EventManager.ins().registListener(EventTag.DO_ADD_TO_BLACK_LIST, eventListener);
        EventManager.ins().registListener(EventTag.DO_REMOVE_BLACK_LIST, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().registListener(EventTag.ON_STORY_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_ARTICLE_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_ANSWER_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_QUESTION_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_ADD, eventListener);

        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(currentUser.getUserId())) {
            //当前用户为自己不用查询
        } else {
            getUserFollowState();
        }
        UserManager.ins().addBrowserHistory(TAG, AppKey.TYPE_USER, currentUser.getUserId());
        API_Statistics.ins().addDetailData(TAG, this, AppKey.TYPE_USER, currentUser.getUserId());
    }


    @Override
    public void initData() {
        getUserInfo();
        pageNum = 1;
        API_Found.ins().getSomeoneDynamicList(TAG, currentUser.getUserId(), pageNum, AppKey.PAGE_SIZE, CacheMode.DEFAULT, refreshCallback);
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(currentUser.getUserId())) {
            getUserPhoto(currentUser.getUserId());
        } else {
            getOthersPhoto(currentUser.getUserId());
        }
    }

    private void getUserInfo() {
        API_User.ins().getUserInfoById(TAG, currentUser.getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    if (!TextUtils.isEmpty(resultValue)) {
                        UserinfoDetailResult result = new Gson().fromJson(resultValue, UserinfoDetailResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getUser()) {
                            if (null != result.getRes().getUser()) {
                                currentUser = result.getRes().getUser();
                                currentUser.setUserId(result.getRes().getUser().getId());
                                headView.setData(currentUser);
                                refreshUi(currentUser);
                            }
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                }
                return false;
            }
        });
    }

    private int pageNum = 1;
    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_STORY_DELETED:
                case EventTag.ON_ANSWER_DELETED:
                case EventTag.ON_ARTICLE_DELETED:
                case EventTag.ON_QUESTION_DELETED:
                    getUserInfo();
                    break;
                case EventTag.ON_DYNAMIC_ADD:
                    pageNum = 1;
                    API_Found.ins().getSomeoneDynamicList(TAG, currentUser.getUserId(), pageNum, AppKey.PAGE_SIZE, CacheMode.DEFAULT, refreshCallback);
                    break;
                case EventTag.DO_REPORT:
                    UserManager.ins().report(TAG, AppKey.TYPE_USER, currentUser.getUserId());
                    break;
                case EventTag.ABLUM_CHANGED:
                    initData();
                    break;
                case EventTag.ADD_ABLUM:
                    imagePicker.setSelectLimit(AppKey.IMAGE_SIZE - imageList.size() + 1);
                    Intent intent = new Intent(SomeoneHomepageActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, ImagePickerManager.RESULT_CODE_GALLERY);
                    break;
                case EventTag.DELETE_ABLUM:
                    int postion = (int) dataobj;
                    if (imageList.size() <= postion)
                        return;
                    imageList.remove(postion);
                    String imageUrls = getCurrentImages();
                    if (imageUrls.endsWith(AppKey.SEPARATOR))
                        imageUrls = imageUrls.substring(0, imageUrls.length() - 1);
                    updateAlbum(imageUrls);
                    break;
                case EventTag.ACCOUNT_UPDATE_INFO:
                    getUserInfo();
                    break;
                case EventTag.ON_DYNAMIC_DELETED:
                    String deleteId = (String) dataobj;
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(deleteId)) {
                            dataList.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    getUserInfo();
                    break;
                case EventTag.DO_CANCEL_FOLLOW:
                    cancelFollowUser();
                    break;
                case EventTag.DO_ADD_TO_BLACK_LIST:
                    showAddToBlackDialog();
                    break;
                case EventTag.DO_REMOVE_BLACK_LIST:
                    removeBlackList();
                    break;
                case EventTag.ACCOUNT_LOGIN:
                    if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(currentUser.getUserId())) {
                        //当前用户为自己不用查询
                    } else {
                        getUserFollowState();
                    }
                    UserManager.ins().addBrowserHistory(TAG, AppKey.TYPE_USER, currentUser.getUserId());
                    API_Statistics.ins().addDetailData(TAG, SomeoneHomepageActivity.this, AppKey.TYPE_USER, currentUser.getUserId());
                    initData();
                    break;
            }

        }
    };

    /**
     * 拉黑对话框
     */
    private void showAddToBlackDialog() {
        TipDialog dialog = new TipDialog(this);
        dialog.setPromptTitle("确认将该用户加入黑名单？");
        dialog.setTextDes("拉黑后，对方将不能关注你、给你发消息、回答/评论/回复你实名发布的内容、邀请你回答问题等，并自动从你的粉丝和关注列表移除。");
        dialog.setButton1(getString(R.string.action_ok), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                addToBlackList();
                dialog.dismiss();
            }
        });
        dialog.setButton2(getString(R.string.action_cancel), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 关注拉黑人的对话框
     */
    private void showFollowBlackListPeopleDialog() {
        TipDialog dialog = new TipDialog(this);
        dialog.setTextDes("确认取消拉黑并关注该用户？");
        dialog.setButton1(getString(R.string.action_ok), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                followUser();
                dialog.dismiss();
            }
        });
        dialog.setButton2(getString(R.string.action_cancel), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 加入黑名单
     */
    private void addToBlackList() {
        API_User.ins().addToBackList(TAG, currentUser.getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                    if (null != result && null != result.getRes()) {
                        friendType = result.getRes().getFriend().getFriendType();
                        showTalkView();
                        ToastUtil.showToast("拉黑成功");
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 移出黑名单
     */
    private void removeBlackList() {
        API_User.ins().removeBackList(TAG, currentUser.getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                    if (null != result && null != result.getRes()) {
                        friendType = result.getRes().getFriend().getFriendType();
                        showTalkView();
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    String imageUrls = "";

    private int index;

    private void uploadImage(final ArrayList<ImageItem> images, int i) {
        if (i == 0) {
            imageUrls = "";
        }
        index = i;
        if (index < images.size()) {
            API_App.ins().uploadData(TAG, images.get(index).path, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    index++;
                    if (errCode == ResponseResult.ResultStatus.OK) {
                        UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                            String url = result.getRes().getHashmap().getImgurl();
                            imageUrls += url + AppKey.SEPARATOR;
                            if (index == images.size()) {
                                if (!TextUtils.isEmpty(imageUrls)) {
                                    imageUrls = getCurrentImages() + imageUrls.substring(0, imageUrls.length() - 1);
                                }
                                if (isAdded) {
                                    API_User.ins().addAlbum(TAG, UserManager.ins().getUserId(), imageUrls, callback);
                                } else {
                                    API_User.ins().updateAlbum(TAG, UserManager.ins().getUserId(), albumId, imageUrls, callback);
                                }
                            } else {
                                uploadImage(images, index);
                            }
                        }
                    } else {
                        if (index == images.size()) {
                            if (!TextUtils.isEmpty(imageUrls)) {
                                imageUrls = getCurrentImages() + imageUrls.substring(0, imageUrls.length() - 1);
                            }
                            if (isAdded) {
                                API_User.ins().addAlbum(TAG, UserManager.ins().getUserId(), imageUrls, callback);
                            } else {
                                API_User.ins().updateAlbum(TAG, UserManager.ins().getUserId(), albumId, imageUrls, callback);
                            }
                        }
                    }
                    return false;
                }
            });
        }
    }

    private String getCurrentImages() {
        String imageUrl = "";
        for (int i = 0; i < imageList.size(); i++) {
            if (!imageList.get(i).equals(AppKey.ADD_PIC)) {
                imageUrl += imageList.get(i) + AppKey.SEPARATOR;
            }
        }
        return imageUrl;
    }

    private void getUserPhoto(String userId) {
        API_User.ins().getUserAlbumByUserId(TAG, userId, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
                if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    if (imageList != null) {
                        imageList.clear();
                    }
                    AlbumResult result = new Gson().fromJson(resultValue, AlbumResult.class);
                    if (null != result.getRes() && result.getRes().getArraylist() != null) {
                        if (result.getRes().getArraylist().size() > 0) {
                            isAdded = false;
                            if (null != result.getRes().getArraylist().get(0)) {
                                albumId = result.getRes().getArraylist().get(0).getId();
                                if (null != result.getRes().getArraylist().get(0).getImageUrl()) {
                                    imageList.addAll(result.getRes().getArraylist().get(0).getImageUrl());
                                    if (imageList.size() < AppKey.IMAGE_SIZE) {
                                        imageList.add(AppKey.ADD_PIC);
                                    }
                                    adapter.notifyDataSetChanged();
                                    headView.setSelfImage(imageList);
                                }
                            }
                        }
                    }
                    if (imageList.size() == 0) {
                        if (imageList.size() < AppKey.IMAGE_SIZE) {
                            imageList.add(AppKey.ADD_PIC);
                            headView.setSelfImage(imageList);
                        }
                    }
                } else {
                    if (imageList.size() < AppKey.IMAGE_SIZE) {
                        imageList.add(AppKey.ADD_PIC);
                        headView.setSelfImage(imageList);
                    }
                }
                return false;
            }
        });
    }

    private void getOthersPhoto(String userId) {
        API_User.ins().getUserAlbumByUserId(TAG, userId, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
                if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    AlbumResult result = new Gson().fromJson(resultValue, AlbumResult.class);
                    if (null != result.getRes() && result.getRes().getArraylist() != null) {
                        if (result.getRes().getArraylist().size() > 0) {
                            if (null != result.getRes().getArraylist().get(0)) {
                                if (null != result.getRes().getArraylist().get(0).getImageUrl()) {
                                    imageList.addAll(result.getRes().getArraylist().get(0).getImageUrl());
                                    adapter.notifyDataSetChanged();
                                    headView.setOtherSImage(imageList);
                                } else {
                                    headView.setOtherSImage(imageList);
                                }
                            } else {
                                headView.setOtherSImage(imageList);
                            }
                        } else {
                            headView.setOtherSImage(imageList);
                        }
                    } else {
                        headView.setOtherSImage(imageList);
                    }
                } else {
                    headView.setOtherSImage(imageList);
                }
                return false;
            }
        });
    }

    private boolean isAdded = true;
    int albumId;

    /**
     * 删除相片
     */
    public void updateAlbum(String image) {
        API_User.ins().updateAlbum(TAG, UserManager.ins().getUserId(), albumId, image, callback);
    }

    StringResponseCallback callback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
            hideLoadingDialog();
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                imageList.clear();
                getUserPhoto(currentUser.getUserId());
            } else {
                ToastUtil.showToast(errmsg);
            }
            return false;
        }
    };

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getSomeoneDynamicList(TAG, currentUser.getUserId(), pageNum + 1, AppKey.PAGE_SIZE, CacheMode.DEFAULT, moreCallback);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        ViewGT.gotoDetailActivity(this, dataList.get(position));
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                DynamicListResult result = new Gson().fromJson(resultValue, DynamicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }

            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                DynamicListResult result = new Gson().fromJson(resultValue, DynamicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    private void refreshUi(User user) {
        if (null != user) {
            if (!TextUtils.isEmpty(user.getName())) {
                tvUserName.setText(user.getName());
                tvHomepageUserName.setText(user.getName());
            }
            BitmapLoader.ins().loadImage(user.getImage(), rivAvatar);
            if (UserManager.ins().getUserId().equals(user.getUserId())) {
                ivReport.setVisibility(View.GONE);
                ivEdit.setVisibility(View.VISIBLE);
                llBottomContainer.setVisibility(View.GONE);
            } else {
                ivReport.setVisibility(View.VISIBLE);
                ivEdit.setVisibility(View.GONE);
                llBottomContainer.setVisibility(View.VISIBLE);
            }

            tvLevel.setText(getString(R.string.userLevel, String.valueOf(user.getLevelId())));
            if (!TextUtils.isEmpty(user.getIntroduce())) {
                tvDesc.setText(user.getIntroduce());
            }
            if (user.getSex() == 1) {
                Drawable manDrawable = getResources().getDrawable(R.drawable.ic_male);
                manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(), manDrawable.getMinimumHeight());
                tvAgeInfo.setCompoundDrawables(manDrawable, null, null, null);
                tvAgeInfo.setCompoundDrawablePadding((int) RT.getDensity() * 1);
                tvAgeInfo.setSelected(false);
                ivHeaderBg.setBackgroundResource(R.drawable.ic_head_boy);
            } else if (user.getSex() == 2) {
                Drawable manDrawable = getResources().getDrawable(R.drawable.ic_female);
                manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(), manDrawable.getMinimumHeight());
                tvAgeInfo.setCompoundDrawables(manDrawable, null, null, null);
                tvAgeInfo.setCompoundDrawablePadding((int) RT.getDensity() * 1);
                tvAgeInfo.setSelected(true);
                ivHeaderBg.setBackgroundResource(R.drawable.ic_head_girl);
            }
            tvAgeInfo.setText(String.valueOf(user.getAge()));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().removeListener(EventTag.ADD_ABLUM, eventListener);
        EventManager.ins().removeListener(EventTag.ABLUM_CHANGED, eventListener);
        EventManager.ins().removeListener(EventTag.DELETE_ABLUM, eventListener);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.DO_CANCEL_FOLLOW, eventListener);
        EventManager.ins().removeListener(EventTag.DO_ADD_TO_BLACK_LIST, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REMOVE_BLACK_LIST, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().removeListener(EventTag.ON_STORY_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_ARTICLE_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_ANSWER_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_QUESTION_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_ADD, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePickerManager.RESULT_CODE_ITEMS) {
            if (data == null) {
                return;
            }
            if (requestCode == ImagePickerManager.RESULT_CODE_GALLERY) {//从图库返回
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePickerManager.EXTRA_RESULT_ITEMS);
                uploadImage(images, 0);
                showLoadingDialog();
            }
        } else if (requestCode == ImagePickerManager.REQUEST_CODE_TAKE) {
            //发送广播通知图片增加了
            ImagePickerManager.galleryAddPic(this, imagePicker.getTakeImageFile());
            ImageItem imageItem = new ImageItem();
            imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
            imagePicker.clearSelectedImages();
            imagePicker.addSelectedImageItem(0, imageItem, true);
            ArrayList<ImageItem> images = new ArrayList<>();
            images.add(imageItem);
            uploadImage(images, 0);
            showLoadingDialog();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isFromPush) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack://返回
                finish();
                break;
            case R.id.rivAvatar://编辑头像
                if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(currentUser.getUserId())) {
                    EditAvatarActivity.start(SomeoneHomepageActivity.this, currentUser);
                } else {
                    ArrayList<ImageItem> images = new ArrayList<>();
                    ImageItem imageItem = new ImageItem();
                    imageItem.url = currentUser.getImage();
                    imageItem.isFromNet = true;
                    images.add(imageItem);
                    Intent intent = new Intent(this, ImagePreviewTopicActivity.class);
                    intent.putExtra(ImagePickerManager.EXTRA_SELECTED_IMAGE_POSITION, 0);
                    intent.putExtra(ImagePickerManager.EXTRA_IMAGE_ITEMS, images);
                    intent.putExtra(ImagePreviewActivity.ISORIGIN, false);
                    startActivity(intent);  //如果是多选，点击图片进入预览界面
                }
                break;
            case R.id.ivReport://举报
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(SomeoneHomepageActivity.this);
                    return;
                }
                ReportSomeonePop reportPop = new ReportSomeonePop(this, friendType);
                reportPop.show(getWindow().getDecorView());
                break;
            case R.id.ivEdit://编辑
                ModtifyUserInfoActivity.start(this);
                break;
            case R.id.llFollowContainer:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                if (friendType == AppKey.RELATIONSHIP_TYPE_BLACK) {
                    showFollowBlackListPeopleDialog();
                } else {
                    followUser();
                }
                break;
            case R.id.llTalkContainer:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(SomeoneHomepageActivity.this);
                    return;
                }
                SessionHelper.startP2PSession(this, UserManager.ins().getChatId(currentUser.getUserId()), currentUser.getName());
                break;
        }
    }

    /**
     * 获取用户关注状态
     */
    private void getUserFollowState() {
        if (!UserManager.ins().isLogin()) {
            return;
        }
        API_User.ins().getUserFollowStated(TAG, currentUser.getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getFriend()) {
                        friendType = result.getRes().getFriend().getFriendType();
                    }
                }
                showTalkView();
                return false;
            }
        });
    }

    private void showTalkView() {
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(currentUser.getUserId())) {
            llBottomContainer.setVisibility(View.GONE);
        } else {
            llBottomContainer.setVisibility(View.VISIBLE);
            if (AppKey.RELATIONSHIP_TYPE_FRIEND == friendType || AppKey.RELATIONSHIP_TYPE_FOLLOW == friendType) {
                llTalkContainer.setVisibility(View.VISIBLE);
                llFollowContainer.setVisibility(View.GONE);
            } else {
                llTalkContainer.setVisibility(View.VISIBLE);
                llFollowContainer.setVisibility(View.VISIBLE);
            }
        }
    }

    int friendType = AppKey.RELATIONSHIP_TYPE_NORMAL;

    /**
     * 关注
     */
    private void followUser() {
        llFollowContainer.setEnabled(false);
        API_User.ins().followUser(TAG, UserManager.ins().getUserId(), currentUser.getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                llFollowContainer.setEnabled(true);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                    if (null != result && null != result.getRes()) {
                        friendType = result.getRes().getFriend().getFriendType();
                        showTalkView();
                    }
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    if (currentUser.getSex() == AppKey.SEX_MAN) {
                        ToastUtil.showToast("由于对方的设置，你不能关注他");
                    } else {
                        ToastUtil.showToast("由于对方的设置，你不能关注她");
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    /**
     * 取消关注
     */
    private void cancelFollowUser() {
        API_User.ins().cancelFollowUser(TAG, UserManager.ins().getUserId(), currentUser.getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                    if (null != result && null != result.getRes()) {
                        friendType = result.getRes().getFriend().getFriendType();
                        showTalkView();
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
